<?php
namespace app\admin\controller;
use app\admin\model\Uncustomers;
use app\admin\model\Users;
use app\admin\controller\AdminAuth;
use think\Exception;
use think\Validate;
use think\File;
use think\Image;
use think\Db;
use think\Request;
class UncustomersController extends AdminAuth
{
    //模块基本信息
    private $data = array(
        'module_name' => '未分配客户',
        'module_url' => '/admin/Uncustomers/',
        'module_slug' => 'Customers',
        'upload_path' => UPLOAD_PATH,
        'upload_url' => '/public/uploads/',
    );

    public function index(){
        $where = array();
        input('mobile') ? $where['mobile'] = input('mobile') : false;
        input('c_nickname') ? $where['c_nickname'] = input('c_nickname') : false;
        $list = Db::name('uncustomers')->where($where)->where(['status'=>1])->order('uncustomers_id DESC')->paginate(10);
        $this->assign('data',$this->data);
        $this->assign('list',$list);
        return view();
    }
    /**
     * [read 读取用户数据]
     */
    public function read(Request $request)
    {
        $uncustomers_id = input('uncustomers_id');
        //默认值设置
        $item = Db::name('uncustomers')->where(['uncustomers_id'=>$uncustomers_id])->find();
        $this->assign('item',$item);
        $this->assign('data',$this->data);
        return view();
    }
    /**
     * [update 更新用户数据，read()提交表单数据到这里]
     */
    public function update($uncustomers_id)
    {
        $uncustomers = new Uncustomers();
        //$data = input('post.');
        $data['name'] = input('name');
        $data['c_nickname'] = input('c_nickname');
        $data['mobile'] = input('mobile');
        $data['sex'] = input('sex');
        $data['customer_levlel'] = input('customer_levlel');
        $data['customer_type'] = input('customer_type');
        $data['remark'] = input('remark');
        $data['addtime'] = time();
        $rule = [
            //字段验证
            'name|用户名' => 'require',
            'mobile|手机号'   => 'length:11',
        ];
        // 数据验证
        $validate = new Validate($rule);
        $result   = $validate->check($data);
        if(!$result){
            return  $this->error($validate->getError());
        }
        if ($uncustomers->validate(true)->where(['uncustomers_id'=>$uncustomers_id])->update($data)) {
            return $this->success('信息更改成功',$this->data['module_url'],'','1');
        } else {
            return $this->error($uncustomers->getError());
        }
    }

    /**
     * [delete 删除用户数据(伪删除)]
     */
    public function delete($uncustomers_id)
    {
        // 真.删除，不想用伪删除，请用这段
        $uncustomer = Uncustomers::get($uncustomers_id);
        $data['uncustomers_id'] = $uncustomers_id;
        if ($uncustomer) {
            $uncustomer->delete();
            $data['error'] = 0;
            $data['msg'] = '删除成功';
        } else {
            $data['error'] = 1;
            $data['msg'] = '删除失败';
        }
        return $data;
    }

    //分配客户给销售用户
    public function distribut(){
        $uncustomers_id_array = input('uncustomers_id_array');
        $users = array();
        if (!empty($uncustomers_id_array)) {
            $user_where = array(
                'uncustomers_id' => array('IN', $uncustomers_id_array)
            );
            $uncustomers = Db::name('uncustomers')->field('uncustomers_id,c_nickname')->where($user_where)->select();
        }

        $users = Db::name('users')->field('id,nickname')->select();

        $this->assign('uncustomers',$uncustomers);
        $this->assign('users',$users);
        return view();
    }
    //分配客户给销售用户(提交)
    public function dodistribut(){
        $uncustomers_id = input('post.')['uncustomers_id']; //二维数组
        $user_id = input('user_id'); //即将分配的所属id
        foreach($uncustomers_id as $vid){
            Db::startTrans();
            try{
                $uncustomers_msg = Db::name('uncustomers')->where(['uncustomers_id'=>$vid])->field('name,mobile,sex,c_nickname,header_pic,customer_levlel,customer_type,remark')->find();
                $uncustomers_msg['addtime'] = time();
                $customers_id = Db::name('customers')->insertGetId($uncustomers_msg); //插入客户表获取id
                $data = ['user_id'=>$user_id,'customers_id'=>$customers_id,'addtime'=>time()];
                Db::name('distribution')->insert($data);  //插入分配表
                Db::name('uncustomers')->where(['uncustomers_id'=>$vid])->update(['status'=>2]);  //逻辑删除未分配表  默认：status=1；删除：status=2;
                Db::commit();
                $msg = ['code'=>1,'msg'=>'分配成功！'];
            }catch (Exception $e){
                Db::rollback();
                $msg = ['code'=>0,'msg'=>'分配失败！'];
            }
        }
        return json($msg);

    }
    //导入客户资料
    public function saveImport(){
        //import('phpexcel.PHPExcel', EXTEND_PATH);//方法二
        vendor("phpoffice.Classes.PHPExcel"); //方法一
        $objPHPExcel = new \PHPExcel();
        //获取表单上传文件
        $file = request()->file('excel');
        $info = $file->validate(['size'=>156780,'ext'=>'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'static'. DS .'admin'. DS . 'excel');
        if($info){
            $exclePath = $info->getSaveName();  //获取文件名
            $file_name = ROOT_PATH . 'public' . DS . 'static'. DS .'admin'. DS . 'excel' . DS . $exclePath;   //上传文件的地址
            $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
            $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8');  //加载文件内容,编码utf-8
            echo "<pre>";
            $excel_array=$obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
            array_shift($excel_array);  //删除第一个数组(标题);
            $data = [];
            $i=0;
            foreach($excel_array as $k=>$v) {
                $data[$k]['name'] = $v[0];       //客户姓名
                $data[$k]['c_nickname'] = $v[1];  //客户昵称
                $data[$k]['mobile'] = $v[2];      //电话
                $data[$k]['sex'] = $v[3];         //性别
                $data[$k]['customer_levlel'] = $v[4];  //客户等级
                $data[$k]['customer_type'] = $v[5];   //客户类别
                $data[$k]['remark'] = $v[6];          //备注
                $data[$k]['addtime'] = time();          //导入时间
                $i++;
            }

            $success=Db::name('uncustomers')->insertAll($data); //批量插入数据
            $error=$i-$success;
            $msg = "总{$i}条，成功{$success}条，失败{$error}条。";
            $this->success($msg,$this->data['module_url']);
        }else{
            // 上传失败获取错误信息
            echo $file->getError();
        }
    }
}